<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="queryParams.content"
              placeholder="请输入内容"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用户ID" prop="userId">
            <el-input
              v-model="queryParams.userId"
              placeholder="请输入用户ID"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="可见性" prop="visibilityType">
            <el-select v-model="queryParams.visibilityType" placeholder="请选择可见性" clearable style="width: 100%">
              <el-option label="树洞" value="my_tree_hole" />
              <el-option label="公开圈子" value="public_circle" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="是否匿名" prop="isAnonymousInPublic">
            <el-select v-model="queryParams.isAnonymousInPublic" placeholder="请选择是否匿名" clearable style="width: 100%">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="text-align: right; padding-top: 4px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:entries:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:entries:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:entries:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:entries:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="entriesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="条目ID" align="center" prop="entryId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="可见性" align="center">
        <template slot-scope="scope">
          {{ formatVisibility(scope.row.visibilityType) }}
        </template>
      </el-table-column>
      <el-table-column label="是否匿名" align="center">
        <template slot-scope="scope">
          {{ formatAnonymous(scope.row.isAnonymousInPublic) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞数" align="center" prop="likesCount" />
      <el-table-column label="评论数" align="center" prop="commentsCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:entries:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:entries:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改树洞内容对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="是否匿名" prop="isAnonymousInPublic">
          <el-switch
            v-model="form.isAnonymousInPublic"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="点赞数" prop="likesCount">
          <el-input-number v-model="form.likesCount" :min="0" :precision="0" :step="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="评论数" prop="commentsCount">
          <el-input-number v-model="form.commentsCount" :min="0" :precision="0" :step="1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEntries, getEntries, delEntries, addEntries, updateEntries } from "@/api/system/entries";

export default {
  name: "Entries",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 圈子发帖表格数据
      entriesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        content: null,
        visibilityType: null,
        isAnonymousInPublic: null,
        createdAt: null,
        updatedAt: null,
        likesCount: null,
        commentsCount: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        visibilityType: [
          { required: true, message: "可见性不能为空", trigger: "change" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedAt: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      },
      // 日期范围
      dateRange: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询树洞内容列表 */
    getList() {
      this.loading = true;
      listEntries(this.queryParams).then(response => {
        this.entriesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 格式化可见性 */
    formatVisibility(visibilityType) {
      const visibilityMap = {
        'public_circle': '公开圈子',
        'my_tree_hole': '树洞',
        'private': '私密'
      };
      return visibilityMap[visibilityType] || visibilityType;
    },
    /** 格式化是否匿名 */
    formatAnonymous(isAnonymous) {
      if (isAnonymous === 'TRUE' || isAnonymous === true || isAnonymous === 1 || isAnonymous === '1') {
        return '是';
      }
      return '否';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        entryId: null,
        userId: null,
        content: null,
        visibilityType: null,
        isAnonymousInPublic: 0,
        createdAt: null,
        updatedAt: null,
        likesCount: null,
        commentsCount: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.beginCreatedAt = this.dateRange[0];
        this.queryParams.endCreatedAt = this.dateRange[1];
      } else {
        this.queryParams.beginCreatedAt = undefined;
        this.queryParams.endCreatedAt = undefined;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.entryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加树洞内容";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const entryId = row.entryId || this.ids
      getEntries(entryId).then(response => {
        this.form = response.data;
        // 确保isAnonymousInPublic是数字类型
        if (this.form.isAnonymousInPublic !== null && this.form.isAnonymousInPublic !== undefined) {
          // 将各种可能的值转换为数字值
          this.form.isAnonymousInPublic = this.form.isAnonymousInPublic === true || 
                                         this.form.isAnonymousInPublic === 1 || 
                                         this.form.isAnonymousInPublic === '1' ||
                                         this.form.isAnonymousInPublic === 'TRUE' ? 1 : 0;
        }
        this.open = true;
        this.title = "修改树洞内容";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保提交前isAnonymousInPublic是数字类型
          if (this.form.isAnonymousInPublic !== null && this.form.isAnonymousInPublic !== undefined) {
            this.form.isAnonymousInPublic = Number(this.form.isAnonymousInPublic);
          }
          
          if (this.form.entryId != null) {
            updateEntries(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEntries(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const entryIds = row.entryId || this.ids;
      this.$modal.confirm('是否确认删除树洞内容编号为"' + entryIds + '"的数据项？').then(function() {
        return delEntries(entryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/entries/export', {
        ...this.queryParams
      }, `entries_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
